import Snake from "./Snake";
import Food from "./Food";
import ScorePanel from "./ScorePanel";
//游戏控制器类
class GameControl {
    snake: Snake;
    food: Food;
    scorePanel: ScorePanel;
    //创建一个属性来存储蛇的移动方向
    direction: string = '';
    //创建一个属性记录游戏是否结束
    isLive = true;
    //定义一个数据，用来控制蛇不能掉头
    index: number;

    constructor() {
        this.snake = new Snake();
        this.food = new Food();
        this.scorePanel = new ScorePanel();
        this.index = 0;
        //游戏开始
        this.init();
    }
    //游戏的初始化方法，调用后游戏就开始
    init() {
        //绑定键盘事件
        //bind方法用于创建一个新函数，函数的this指定为bind的第一个参数
        document.addEventListener('keydown', this.keyDownHandler.bind(this));
        this.run();
    }
    //创建键盘按下的响应函数
    keyDownHandler(e: KeyboardEvent) {
        // console.log(e.key)
        this.direction = e.key;
    }
    //控制蛇移动
    run() {
        let X = this.snake.X;
        let Y = this.snake.Y;
        //根据按键方向修改X,Y值
        switch (this.direction) {
            case "ArrowUp":
                if(this.index !== 1){
                    Y -= 10;
                    this.index = -1; 
                }else{
                    Y += 10;
                }
                break;
            case "ArrowDown":
                if(this.index !== -1){
                    Y += 10;
                    this.index = 1; 
                }else{
                    Y -= 10;
                }
                break;
            case "ArrowLeft":
                if(this.index !== 2){
                    X -= 10;
                    this.index = -2; 
                }else{
                    X += 10;
                }
                break;
            case "ArrowRight":
                if(this.index !== -2){
                    X += 10;
                    this.index = 2; 
                }else{
                    X -= 10;
                }
                break;
        }
        //吃到食物之后
        if(this.checkEat(X,Y)){
            //改变食物位置
            this.food.change();
            //加分
            this.scorePanel.addScore();
            //加长身体
            this.snake.addBody();
        }
        try{
            this.snake.change(X,Y);
        }catch(e){
            //游戏结束
            //把游戏状态设置为关闭
            this.isLive = false;
            alert('游戏结束');
        }
        if(this.isLive){
            setTimeout(this.run.bind(this),200-(this.scorePanel.level-1)*12)
        }
    }
    //检查蛇是否吃到食物
    checkEat(X:number,Y:number){
        return X === this.food.X && Y === this.food.Y
    }
}
export default GameControl;